import Joi from 'joi';
import debugCheck from '@kuiper-helpers/debug-check';
import * as validation from '../../common/validation';
import extractQueryFieldByJoi from '../helpers/extractQueryFieldByJoi';
import findManyFilter from '../../common/validation/findManyFilter';
import joiOmit from '../helpers/joiOmit';

export const pagination = {
	tags: ['api', 'alertGroup'],
	description: '告警组列表-分页查看',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			page: Joi.number().default(1).description('当前页'),
			perPage: Joi.number().default(10).description('每页条目数'),
			filter: findManyFilter.alertGroup,
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupPagination: Joi.object({
					count: Joi.number().description('总条数'),
					pageInfo: Joi.object({
						currentPage: Joi.number().description('当前页数'),
						perPage: Joi.number().description('每页条数'),
						pageCount: Joi.number().description('总页数'),
						itemCount: Joi.number().description('总条数'),
						hasNextPage: Joi.boolean().description('是否有下一页'),
						hasPreviousPage: Joi.boolean().description('是否有上一页'),
					}),
					items: Joi.array().items(
						validation.alertGroupWithId.append({
							receivers: Joi.array().items(validation.alertReceiverWithId),
						})
					),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { page, perPage, filter },
				} = request;

				return JSON.stringify({
					variables: { page, perPage, filter },
					// #region query
					query: `
						query($page: Int = 1, $perPage: Int = 10, $filter: FilterFindManyAlertGroupInput, $sort: SortFindManyAlertGroupInput = _ID_DESC) {
							AlertGroupPagination(page: $page, perPage: $perPage, filter: $filter, sort: $sort) {
								count
								pageInfo {
									currentPage
									perPage
									pageCount
									itemCount
									hasNextPage
									hasPreviousPage
								}
								items {
									_id
									uid
									name
									receiverIds
									receivers {
										_id
										name
										phone
										email
										enable
										wechat
										isDefault
									}
									enable
									isDefault
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const createOne = {
	tags: ['api', 'alertGroup'],
	description: '创建告警组',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: validation.alertGroup,
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupCreateOne: Joi.object({
					recordId: Joi.string(),
					record: validation.alertGroupWithId,
				}).label('AlertGroupCreateOne'),
			}).label('Data'),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { payload: record } = request;

				return JSON.stringify({
					variables: {
						record,
					},
					// #region query
					query: `
						mutation($record: CreateOneAlertGroupInput!) {
							AlertGroupCreateOne(record: $record) {
								recordId
								record {
									_id
									name
									uid
									receiverIds
									enable
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const updateById = {
	tags: ['api', 'alertGroup'],
	description: '更新告警组',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: joiOmit(validation.alertGroup),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupUpdateById: Joi.object({
					recordId: Joi.string().description('更新记录的ID'),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload,
					params: { alertGroupId },
				} = request;

				return JSON.stringify({
					variables: { filter: { _id: alertGroupId }, record: payload },
					// #region query
					query: `
						mutation($filter: FilterUpdateOneAlertGroupInput!, $record: UpdateOneAlertGroupInput!) {
							AlertGroupUpdateById: AlertGroupUpdateOne(filter: $filter, record: $record) {
								recordId
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const removeById = {
	tags: ['api', 'alertGroup'],
	description: '按ID删除告警组',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		params: Joi.object({
			alertGroupId: Joi.string().required(),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupRemoveMany: Joi.object({
					numAffected: Joi.number().description('删除条数'),
				}).label('AlertGroupRemoveMany'),
			}).label('Data'),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					params: { alertGroupId },
				} = request;

				return JSON.stringify({
					variables: { alertGroupId },
					// #region query
					query: `
						mutation($alertGroupId: MongoID!) {
							AlertGroupRemoveMany(filter: { _ids: [$alertGroupId] }) {
								numAffected
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const removeMany = {
	tags: ['api', 'alertGroup'],
	description: '批量删除告警组',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.array()
			.items(Joi.string().description('告警组ID'))
			.required()
			.description('告警组ID列表'),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupRemoveMany: Joi.object({
					numAffected: Joi.number().description('删除条数'),
				}).label('AlertGroupRemoveMany'),
			}).label('Data'),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { payload } = request;

				return JSON.stringify({
					variables: { _ids: payload },
					// #region query
					query: `
						mutation($_ids: [MongoID]) {
							AlertGroupRemoveMany(filter: { _ids: $_ids }) {
								numAffected
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const count = {
	tags: ['api', 'alertGroup'],
	description: '告警组数量统计',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			filter: findManyFilter.alertGroup,
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupCount: Joi.number().description('数量'),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { filter },
				} = request;

				return JSON.stringify({
					variables: { filter },
					// #region query
					query: `
						query($filter: FilterCountAlertGroupInput) {
							AlertGroupCount(filter: $filter)
						}`,
					// #endregion
				});
			},
		},
	},
};

export const findMany = {
	tags: ['api', 'alertGroup'],
	description: '告警组列表',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		query: findManyFilter.alertGroup.unknown(),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				AlertGroupMany: Joi.array().items(validation.alertGroupWithId),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { query } = request;
				request.log.debug({ query }, '请求告警组列表');

				return JSON.stringify({
					variables: {
						filter: extractQueryFieldByJoi({
							query,
							schema: validation.alertGroupWithId,
						}),
					},
					// #region query
					query: `
						query($filter: FilterFindManyAlertGroupInput) {
							AlertGroupMany(filter: $filter, limit: 0) {
								_id
								name
								uid
								receiverIds
								enable
								isDefault
							}
						}`,
					// #endregion
				});
			},
		},
	},
};
